package com.avengers.common.kit;

import com.avengers.core.bean.enums.FileDirType;
import com.avengers.core.kit.FileKit;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by chenhai on 2018-11-08.
 */
public class ImgKit {

    private static final long MIN_SIZE = 512 * 1024;
    private static final long MAX_SIZE = 1024 * 1024;
    private static final String FORMAT_JPG = "jpg";

    /**
     * 将图片格式转换为jpg，大小调整为55K - 1M之间
     *
     * @return
     */
    public static File getSuitableFile(String filePath) throws IOException {
        return getSuitableFile(filePath, null);
    }

    /**
     * @param filePath 图片路径
     * @param maxPx    最大像素
     * @return 新文件
     * @throws IOException
     */
    public static File getSuitableFile(String filePath, Integer maxPx) throws IOException {
        File file = new File(filePath);
        boolean endWithJpg = file.getName().toLowerCase().endsWith(FORMAT_JPG);
        if (endWithJpg && sizeSuitable(file) && null == maxPx) {
            return file;
        }
        // 调整图片大小
        if (!sizeSuitable(file)) {
            while (file.length() < MIN_SIZE) {
                ImageResizer.resize(filePath, filePath, 1.5);
            }
            while (file.length() > MAX_SIZE) {
                ImageResizer.resize(filePath, filePath, 0.5);
            }
        }
        // 调整图片格式为jpg
        if (!endWithJpg || null != maxPx) {
            String tempDir = FileKit.getTmpPath(FileDirType.upload);
            tempDir = tempDir.endsWith(File.separator) ? tempDir : tempDir + File.separator;
            String outPutFilePath = tempDir + UUID.randomUUID() + "." + FORMAT_JPG;
            if (!ImageFormatTransfer.transfer(filePath, outPutFilePath, FORMAT_JPG, maxPx)) {
                throw new RuntimeException("file format transfer error");
            }
            FileKit.delete(file);
            file = new File(outPutFilePath);
        }
        return file;
    }

    /**
     * 文件大小是否合适
     *
     * @param file
     * @return
     */
    private static boolean sizeSuitable(File file) {
        long fileSize = file.length();
        return fileSize >= MIN_SIZE && fileSize <= MAX_SIZE;
    }
}
